﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Threading;
using System.Data;
using System.IO;
using System.Windows.Threading;
using System.Runtime.InteropServices;

namespace VideoArchivePreview
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public BackgroundWorker worker = new BackgroundWorker();
        Config_frm cf;
        TC_frm tf;
        Preview_frm pf;
        bool move = false;
        private System.Drawing.Point pt = new System.Drawing.Point();
        public string mediaserver = "";
        public string user = "";
        public string password = "";
        public string path = "";
        public string folder = "";
        public long filelength = 0;
        public static DataTable tb;
        Ftp ftp = null;
        bool error=false;

        public MainWindow()
        {
            InitializeComponent();
            progressBar1.Visibility = Visibility.Hidden;
            progressLabel.Visibility = Visibility.Hidden;
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.ProgressChanged += backgroundWorker1_ProgressChanged;
            button5_Click(this, null);
        }

        private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            progressLabel.Text = e.ProgressPercentage + "%";
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ConfigDataBase cdb = new ConfigDataBase();
                DataTable ctb = cdb.getTable("select * from config where id=1");
                mediaserver = ctb.Rows[0]["mediaserver"].ToString();
                user = ctb.Rows[0]["user"].ToString();
                password = ctb.Rows[0]["password"].ToString();
                path = ctb.Rows[0]["path"].ToString();
                string[] folders = ctb.Rows[0]["folder"].ToString().Split('|');
                cdb = null;
                FtpClient FC = new FtpClient(mediaserver, user, password);

                
               // FC.worker = worker;
               // Directory.SetCurrentDirectory(path);  
                int countItems = 0;
                this.listBox1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { countItems = listBox1.SelectedItems.Count; }));
                string filename="";
                folder = "";
                for (int i = 0; i < countItems; i++)
                {
                    this.listBox1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { filename = ((DataRowView)listBox1.SelectedItems[i])["filename"].ToString(); }));
                    foreach (string fl in folders)
                    {
                        FC.ChangeDir("..");
                        FC.ChangeDir(fl);
                        if (FC.GetFileList().Contains(filename))
                        {
                            folder = fl;
                            break;
                        }
                    }
                    if (!folder.Equals(""))
                    {
                        this.listBox1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { filelength = FC.GetFileSize(((DataRowView)listBox1.SelectedItems[i])["filename"].ToString()); }));
                        //FC.fileLength = filelength;
                        // FC.Download(filename);
                        ftp = new Ftp(mediaserver, user, password, folder);
                        ftp.worker = worker;
                        ftp.Filesize = filelength;
                        path=System.IO.Path.Combine(path,folder);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        ftp.download(filename, System.IO.Path.Combine(path, filename));
                    } 
                    else {
                        MessageBox.Show("Failas: " + filename+" nerastas!");
                        this.button2.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { button2.Content = "Parsiųsti"; }));
                        this.progressBar1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { progressBar1.Visibility = Visibility.Hidden; }));
                    }
                }
            }
            catch (Exception ex) {
                this.button2.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { button2.Content = "Parsiųsti"; }));
                this.progressBar1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { progressBar1.Visibility=Visibility.Hidden; }));
                MessageBox.Show("Error: " + ex.Message);
                error = true;
            }
        }

        private void worker_RunWorkerCompleted(object sender,
                                               RunWorkerCompletedEventArgs e)
        {
            //update ui once worker complete his work
            ftp = null;
            button3.IsEnabled = true;
            listBox1.IsEnabled = true;
            textBox1.IsEnabled = true;
            button2.Content = "Parsiųsti";
            progressBar1.Visibility = Visibility.Hidden;
            progressLabel.Visibility = Visibility.Hidden;
            if (!error)
            {
               // MessageBox.Show("Parsiųsta!");
            }
            error = false;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (ftp != null)
            {
                ftp.ftpResponse.Close();
            }
            worker.CancelAsync();
            if (cf!=null) {cf.Close();}
             if (tf!=null) {tf.Close();}
             if (pf!=null) {pf.Close();}
            Close();
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (tf != null) {
                this.Owner = null; 
                tf.Close(); 
                tf = null;
            }
            button3.Visibility = Visibility.Hidden;
            button5.Visibility = Visibility.Visible;
            cf = new Config_frm();
            ConfigDataBase cdb = new ConfigDataBase();
            DataTable ctb = cdb.getTable("select * from config where id=1");
            mediaserver = ctb.Rows[0]["mediaserver"].ToString();
            user = ctb.Rows[0]["user"].ToString();
            password = ctb.Rows[0]["password"].ToString();
            path = ctb.Rows[0]["path"].ToString();
            folder = ctb.Rows[0]["folder"].ToString();
            cf.textBox1.Text = mediaserver;
            cf.textBox2.Text = user;
            cf.textBox3.Password = password;
            cf.textBox4.Text = path;
            cf.textBox5.Text = folder;
            cf.Height = this.Height;
            cf.Left = this.Left;
            cf.Top = this.Top;
           // cf.Owner = this;
            cf.Show();
            this.Owner = cf;
            this.Activate();
          //  this.Activate();
           // this.Focus();
           // cf.Owner = this;
            double leftpos=cf.Left;
            while (leftpos > this.Left - cf.Width+50)
            {
                leftpos = leftpos - 10;
                cf.Left = leftpos;
                Thread.Sleep(5);
            }
            Functionality.orderWindows();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            move = true;
            this.pt = System.Windows.Forms.Control.MousePosition;
        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            move = false;
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (move)
            {
                /* this.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                this.Top += (System.Windows.Forms.Control.MousePosition.Y - this.pt.Y);
                if (cf != null)
                {
                    cf.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                    cf.Top += (System.Windows.Forms.Control.MousePosition.Y - this.pt.Y);
                }
                if (tf != null)
                {
                    tf.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                    tf.Top += (System.Windows.Forms.Control.MousePosition.Y - this.pt.Y);
                }
                if (pf != null)
                {
                    pf.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                    pf.Top += (System.Windows.Forms.Control.MousePosition.Y - this.pt.Y);
                }
                this.pt = System.Windows.Forms.Control.MousePosition;*/
                this.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                this.Top += (System.Windows.Forms.Control.MousePosition.Y - this.pt.Y);
                if (cf != null)
                {
                    cf.Left += (System.Windows.Forms.Control.MousePosition.X - this.pt.X);
                    cf.Left = this.Left - cf.Width + 50;
                    cf.Top=this.Top;
                }
                if (tf != null)
                {
                    tf.Left = this.Left - tf.Width + 50;
                    tf.Top = this.Top;
                }
                if (pf != null)
                {
                    pf.Left = this.Left + this.Width - 50;
                    pf.Top = this.Top;
                }
                this.pt = System.Windows.Forms.Control.MousePosition;
            }
        }

        private void Window_MouseLeave(object sender, MouseEventArgs e)
        {
            move = false;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (button2.Content.Equals("Parsiųsti"))
            {
                if (listBox1.SelectedIndex > -1)
                {
                    progressBar1.Visibility = Visibility.Visible;
                    progressLabel.Visibility = Visibility.Visible;
                    button3.IsEnabled = false;
                    listBox1.IsEnabled = false;
                    textBox1.IsEnabled = false;
                    button2.Content = "Atšaukti";
                    worker.RunWorkerAsync();
                }
                else { MessageBox.Show("Pasirinkite parsisiunčiamą failą!"); }
            }
            else
            {
                button3.IsEnabled = true;
                listBox1.IsEnabled = true;
                textBox1.IsEnabled = true;
                button2.Content = "Parsiųsti";
                if (ftp != null)
                {
                    ftp.ftpResponse.Close();
                }
                worker.CancelAsync();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            getftplist();
        }

        public void getftplist()
        {
            try
            {

                ConfigDataBase cdb = new ConfigDataBase();
                DataTable ctb = cdb.getTable("select * from config where id=1");
                folder = ctb.Rows[0]["folder"].ToString();
                mediaserver = ctb.Rows[0]["mediaserver"].ToString();
                user = ctb.Rows[0]["user"].ToString();
                password = ctb.Rows[0]["password"].ToString();
                if (folder.Equals("reklama") || folder.Equals("anonsai"))
                {
                    
                    FtpClient FC = new FtpClient(mediaserver, user, password);
                    listBox1.Items.Clear();
                    tb = new DataTable();
                    tb.Columns.Add("id", typeof(int));
                    tb.Columns.Add("filename", typeof(string));
                    tb.Columns.Add("pav", typeof(string));
   
                    // Here we add five DataRows.
                    int id = 1;
                    foreach (string st in FC.GetFileList())
                    {
                         tb.Rows.Add(id, st, st);
                         id++;
                    }
                    listBox1.ItemsSource = tb.DefaultView;
                }
                else
                {

                    string server = "192.168.100.100\\SQLEXPRESS";
                    string dbuser = "sa";
                    string pass = "tornado";
                    string database = "PASystem";
                    DataBase db = new DataBase(server, dbuser, pass, database);
                    tb = db.getTable("select va.id as id,filename,case ar.id when null then ara.[Lietuviškas pavadinimas] else  ar.[Lietuviškas pavadinimas] end as pav,COALESCE(ar.id,ara.id) archid from VideoArch va left join Archyvas$ ar on va.archid=ar.id left join Archyvas$Archyve ara on va.archid=ara.id");
                    listBox1.ItemsSource = tb.DefaultView;
                    if (radioButton1.IsChecked == true)
                    {
                        listBox1.ItemTemplate = (DataTemplate)FindResource("UserTemplate1");
                    }
                    if (radioButton2.IsChecked == true)
                    {
                        listBox1.ItemTemplate = (DataTemplate)FindResource("UserTemplate2");
                    }
                }
              //  if (listBox1.Items.Count>0) {listBox1.SelectedIndex=0;}
               /* string col="filename";
                if (radioButton1.IsChecked==true)
                {
                   col="filename";
                }
                if (radioButton2.IsChecked == true)
                {
                    col = "pav";
                }
                listBox1.Items.Clear();
                foreach (DataRow rw in tb.Rows)
                {
                    listBox1.Items.Add(rw[col].ToString()); 
                }*/

               /* ConfigDataBase cdb = new ConfigDataBase();
                DataTable ctb = cdb.getTable("select * from config where id=1");
                mediaserver = ctb.Rows[0]["mediaserver"].ToString();
                user = ctb.Rows[0]["user"].ToString();
                password = ctb.Rows[0]["password"].ToString();
                FtpClient FC = new FtpClient(mediaserver, user, password);
                listBox1.Items.Clear();
                foreach (string st in FC.GetFileList())
                {
                    listBox1.Items.Add(st);
                }*/
            }
            catch (Exception ex) { //MessageBox.Show("Error: " + ex.Message); 
                getftplist(); }
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            string searchText = textBox1.Text;

           /* listBox1.Items.Filter = delegate(object obj)
            {
                string str = ((DataRowView)obj)["filename"].ToString();
                if (String.IsNullOrEmpty(str)) return false;
                int index = str.IndexOf(searchText, 0);

                return (index > -1);
            };*/
            string filterExp = "filename Like '%" + searchText + "%'";
            if (radioButton1.IsChecked == true)
            {
                filterExp = "filename Like '%" + searchText + "%'";
            }
            if (radioButton2.IsChecked == true)
            {
                filterExp = "pav Like '%" + searchText + "%'";
            }
            DataRow[] foundrows = tb.Select(filterExp);
            DataTable tb1 = tb;
            if (foundrows.Length > 0) tb1=foundrows.CopyToDataTable();

            listBox1.ItemsSource = tb1.DefaultView;
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {

         //   MessageBox.Show("My value: " + ((DataRowView)listBox1.SelectedItem)["filename"].ToString());
            getftplist();
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if (cf != null) {
                this.Owner = null; 
                cf.Close(); 
                cf = null; 
            }
            button3.Visibility = Visibility.Visible;
            button5.Visibility = Visibility.Hidden;
            tf = new TC_frm();
            tf.Height = this.Height;
            tf.Left = this.Left;
            tf.Top = this.Top;

            if (listBox1.SelectedIndex>-1) { getTC();}
            // cf.Owner = this;
            tf.Show();
           // try
           // {
                this.Owner = tf;
            //}
           // catch (Exception ex) { }
            this.Activate();
            //  this.Activate();
            // this.Focus();
            // cf.Owner = this;
            double leftpos = tf.Left;
            while (leftpos > this.Left - tf.Width + 50)
            {
                leftpos = leftpos - 10;
                tf.Left = leftpos;
                Thread.Sleep(5);
            }
            Functionality.orderWindows();
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            button6.Visibility = Visibility.Hidden;
            pf = new Preview_frm();
            pf.Height = this.Height;
            pf.Left = this.Left+this.Width-pf.Width;
            pf.Top = this.Top;
            pf.Show();
            this.Owner = pf;
            this.Activate();
            double leftpos = pf.Left;
            while (leftpos < this.Left + this.Width  - 50)
            {
                leftpos = leftpos + 10;
                pf.Left = leftpos;
                Thread.Sleep(5);
            }
            Functionality.orderWindows();
        }

        public void getTC()
        {
            if ((pf != null) && (listBox1.SelectedItem!=null))
            {
                pf.mplayer.Source = new Uri("http://lrtvfailai.lrytas.lt/Preview/" + ((DataRowView)listBox1.SelectedItem)["filename"].ToString().Split('.')[0] + ".mp4");   //192.168.0.105/videoarchive/Preview
            }
            if ((tf != null) && ((DataRowView)listBox1.SelectedItem!=null))
            {
                string id = ((DataRowView)listBox1.SelectedItem)["archid"].ToString();
                if (!id.Equals(""))
                {
                    string server = "192.168.100.100\\SQLEXPRESS";
                    string dbuser = "sa";
                    string pass = "tornado";
                    string database = "PASystem";
                    DataBase db = new DataBase(server, dbuser, pass, database);
                    DataTable tb = db.getTable("select * from Archyvas$ where id=" + id);
                    if (tb.Rows.Count > 0)
                    {
                        if (!tb.Rows[0]["Trukmė 1"].ToString().Equals("")) { tf.trukme_1.Text = tb.Rows[0]["Trukmė 1"].ToString(); } else { tf.trukme_1.Text = "00:00:00"; }
                        if (!tb.Rows[0]["Trukmė 2"].ToString().Equals("")) { tf.trukme_2.Text = tb.Rows[0]["Trukmė 2"].ToString(); } else { tf.trukme_2.Text = "00:00:00"; }
                        if (!tb.Rows[0]["TC trukmė"].ToString().Equals("")) { tf.tc_trukme.Text = tb.Rows[0]["TC trukmė"].ToString(); } else { tf.tc_trukme.Text = "00:00:00"; }
                        if (!tb.Rows[0]["TC trukmė"].ToString().Equals("")) { tf.pradzios_tc.Text = tb.Rows[0]["Pradzios TC"].ToString(); } else { tf.pradzios_tc.Text = "00:00:00"; }
                        if (!tb.Rows[0]["I Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_1.Text = tb.Rows[0]["I Įsikirtimas"].ToString(); } else { tf.isikirtimas_1.Text = "00:00:00"; }
                        if (!tb.Rows[0]["II Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_2.Text = tb.Rows[0]["II Įsikirtimas"].ToString(); } else { tf.isikirtimas_2.Text = "00:00:00"; }
                        if (!tb.Rows[0]["III Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_3.Text = tb.Rows[0]["III Įsikirtimas"].ToString(); } else { tf.isikirtimas_3.Text = "00:00:00"; }
                        if (!tb.Rows[0]["IV Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_4.Text = tb.Rows[0]["IV Įsikirtimas"].ToString(); } else { tf.isikirtimas_4.Text = "00:00:00"; }
                        if (!tb.Rows[0]["V Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_5.Text = tb.Rows[0]["V Įsikirtimas"].ToString(); } else { tf.isikirtimas_5.Text = "00:00:00"; }
                        if (!tb.Rows[0]["VI Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_6.Text = tb.Rows[0]["VI Įsikirtimas"].ToString(); } else { tf.isikirtimas_6.Text = "00:00:00"; }
                        if (!tb.Rows[0]["VII Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_7.Text = tb.Rows[0]["VII Įsikirtimas"].ToString(); } else { tf.isikirtimas_7.Text = "00:00:00"; }
                        if (!tb.Rows[0]["VIII Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_8.Text = tb.Rows[0]["VIII Įsikirtimas"].ToString(); } else { tf.isikirtimas_8.Text = "00:00:00"; }
                        if (!tb.Rows[0]["IX Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_9.Text = tb.Rows[0]["IX Įsikirtimas"].ToString(); } else { tf.isikirtimas_9.Text = "00:00:00"; }
                        if (!tb.Rows[0]["X Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_10.Text = tb.Rows[0]["X Įsikirtimas"].ToString(); } else { tf.isikirtimas_10.Text = "00:00:00"; }
                        if (!tb.Rows[0]["XI Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_11.Text = tb.Rows[0]["XI Įsikirtimas"].ToString(); } else { tf.isikirtimas_11.Text = "00:00:00"; }
                        if (!tb.Rows[0]["XII Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_12.Text = tb.Rows[0]["XII Įsikirtimas"].ToString(); } else { tf.isikirtimas_12.Text = "00:00:00"; }
                        if (!tb.Rows[0]["XIII Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_13.Text = tb.Rows[0]["XIII Įsikirtimas"].ToString(); } else { tf.isikirtimas_13.Text = "00:00:00"; }
                        if (!tb.Rows[0]["XIV Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_14.Text = tb.Rows[0]["XIV Įsikirtimas"].ToString(); } else { tf.isikirtimas_14.Text = "00:00:00"; }
                        if (!tb.Rows[0]["XV Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_15.Text = tb.Rows[0]["XV Įsikirtimas"].ToString(); } else { tf.isikirtimas_15.Text = "00:00:00"; }
                        if (!tb.Rows[0]["I Įsikirtimas"].ToString().Equals("")) { tf.isikirtimas_1.Text = tb.Rows[0]["I Įsikirtimas"].ToString(); } else { tf.isikirtimas_1.Text = "00:00:00"; }
                        if (!tb.Rows[0]["Filmo_ID"].ToString().Equals("")) { tf.textBox1.Text = tb.Rows[0]["Filmo_ID"].ToString(); } else { tf.textBox1.Text = ""; }
                        if (!tb.Rows[0]["Žanras"].ToString().Equals("")) { tf.textBox2.Text = tb.Rows[0]["Žanras"].ToString(); } else { tf.textBox2.Text = ""; }
                        if (!tb.Rows[0]["indeksas"].ToString().Equals("")) { tf.textBox3.Text = tb.Rows[0]["indeksas"].ToString(); } else { tf.textBox3.Text = ""; }
                    }
                }
            }
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            getTC();
            if (pf != null) { pf.mplayer.Play(); }
        }

        private void goToPlay(string intime)
        {
            foreach (Window wd in Application.Current.Windows)
            {
                if (wd.Title.Equals("Preview_frm"))
                {
                    try
                    {
                        ((Preview_frm)wd).mplayer.Position = TimeSpan.Parse(intime);
                    }
                    catch (Exception ex) { }
                }
            }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            foreach (Window wd in Application.Current.Windows)
            {
                if (wd.Title.Equals("TC_frm"))
                {
                    if (e.Key == Key.Space)
                    {
                        if (((TC_frm)wd).isikirtimas_15.IsFocused)
                        { ((TC_frm)wd).isikirtimas_1.Focus(); goToPlay(((TC_frm)wd).isikirtimas_1.Text); }
                        else
                            if (((TC_frm)wd).isikirtimas_14.IsFocused)
                            { ((TC_frm)wd).isikirtimas_15.Focus(); goToPlay(((TC_frm)wd).isikirtimas_15.Text); }
                            else
                                if (((TC_frm)wd).isikirtimas_13.IsFocused)
                                { ((TC_frm)wd).isikirtimas_14.Focus(); goToPlay(((TC_frm)wd).isikirtimas_14.Text); }
                                else
                                    if (((TC_frm)wd).isikirtimas_12.IsFocused)
                                    { ((TC_frm)wd).isikirtimas_13.Focus(); goToPlay(((TC_frm)wd).isikirtimas_13.Text); }
                                    else
                                        if (((TC_frm)wd).isikirtimas_11.IsFocused)
                                        { ((TC_frm)wd).isikirtimas_12.Focus(); goToPlay(((TC_frm)wd).isikirtimas_12.Text); }
                                        else
                                            if (((TC_frm)wd).isikirtimas_10.IsFocused)
                                            { ((TC_frm)wd).isikirtimas_11.Focus(); goToPlay(((TC_frm)wd).isikirtimas_11.Text); }
                                            else
                                                if (((TC_frm)wd).isikirtimas_9.IsFocused)
                                                { ((TC_frm)wd).isikirtimas_10.Focus(); goToPlay(((TC_frm)wd).isikirtimas_10.Text); }
                                                else
                                                    if (((TC_frm)wd).isikirtimas_8.IsFocused)
                                                    { ((TC_frm)wd).isikirtimas_9.Focus(); goToPlay(((TC_frm)wd).isikirtimas_9.Text); }
                                                    else
                                                        if (((TC_frm)wd).isikirtimas_7.IsFocused)
                                                        { ((TC_frm)wd).isikirtimas_8.Focus(); goToPlay(((TC_frm)wd).isikirtimas_8.Text); }
                                                        else
                                                            if (((TC_frm)wd).isikirtimas_6.IsFocused)
                                                            { ((TC_frm)wd).isikirtimas_7.Focus(); goToPlay(((TC_frm)wd).isikirtimas_7.Text); }
                                                            else
                                                                if (((TC_frm)wd).isikirtimas_5.IsFocused)
                                                                { ((TC_frm)wd).isikirtimas_6.Focus(); goToPlay(((TC_frm)wd).isikirtimas_6.Text); }
                                                                else
                                                                    if (((TC_frm)wd).isikirtimas_4.IsFocused)
                                                                    { ((TC_frm)wd).isikirtimas_5.Focus(); goToPlay(((TC_frm)wd).isikirtimas_5.Text); }
                                                                    else
                                                                        if (((TC_frm)wd).isikirtimas_3.IsFocused)
                                                                        { ((TC_frm)wd).isikirtimas_4.Focus(); goToPlay(((TC_frm)wd).isikirtimas_4.Text); }
                                                                        else
                                                                            if (((TC_frm)wd).isikirtimas_2.IsFocused)
                                                                            { ((TC_frm)wd).isikirtimas_3.Focus(); goToPlay(((TC_frm)wd).isikirtimas_3.Text); }
                                                                            else
                                                                                if (((TC_frm)wd).isikirtimas_1.IsFocused)
                                                                                { ((TC_frm)wd).isikirtimas_2.Focus(); goToPlay(((TC_frm)wd).isikirtimas_2.Text); }
                        if (((!((TC_frm)wd).isikirtimas_15.IsFocused) && (!((TC_frm)wd).isikirtimas_14.IsFocused) && (!((TC_frm)wd).isikirtimas_13.IsFocused) && (!((TC_frm)wd).isikirtimas_12.IsFocused) &&
                             (!((TC_frm)wd).isikirtimas_11.IsFocused) && (!((TC_frm)wd).isikirtimas_10.IsFocused) && (!((TC_frm)wd).isikirtimas_9.IsFocused) && (!((TC_frm)wd).isikirtimas_8.IsFocused) &&
                            (!((TC_frm)wd).isikirtimas_7.IsFocused) && (!((TC_frm)wd).isikirtimas_6.IsFocused) && (!((TC_frm)wd).isikirtimas_5.IsFocused) && (!((TC_frm)wd).isikirtimas_4.IsFocused) &&
                            (!((TC_frm)wd).isikirtimas_3.IsFocused) && (!((TC_frm)wd).isikirtimas_2.IsFocused) && (!((TC_frm)wd).isikirtimas_1.IsFocused)))
                        { ((TC_frm)wd).isikirtimas_1.Focus(); goToPlay(((TC_frm)wd).isikirtimas_1.Text); }
                        Functionality.orderWindows();
                    }
                }
            }
        }

        private void button7_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
            this.Owner = null;
            foreach (Window wd in Application.Current.Windows)
            {
                if (wd.Title.Equals("Preview_frm"))
                {
                    wd.Visibility = Visibility.Hidden;
                  //  wd.WindowState = WindowState.Minimized;
                }
                if (wd.Title.Equals("TC_frm"))
                {
                    wd.Visibility = Visibility.Hidden;
                  //  wd.WindowState = WindowState.Minimized;
                 }
                if (wd.Title.Equals("Config_frm"))
                {
                    wd.Visibility = Visibility.Hidden;
                   // wd.WindowState = WindowState.Minimized;
                }
            }

        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Normal)
            {
                foreach (Window wd in Application.Current.Windows)
                {
                    if (wd.Title.Equals("Preview_frm"))
                    {
                        wd.Visibility = Visibility.Visible;
                      //  wd.WindowState = WindowState.Normal;
                        
                    }
                    if (wd.Title.Equals("TC_frm"))
                    {
                        wd.Visibility = Visibility.Visible;
                       // wd.WindowState = WindowState.Normal;
                        
                    }
                    if (wd.Title.Equals("Config_frm"))
                    {
                        wd.Visibility = Visibility.Visible;
                       // wd.WindowState = WindowState.Normal;
                    }
                }
                Functionality.orderWindows();
            }
        }

        public Window getWindows(string name)
        {
            Window wt = null;
            foreach (Window wd in Application.Current.Windows)
            {
                if (wd.Title.Equals(name))
                {
                    wt = wd;
                }
            }
            return wt;
        }

        

        private void Window_Activated(object sender, EventArgs e)
        {
            foreach (Window wd in Application.Current.Windows)
            {
                if (wd.Title.Equals("TC_frm"))
                {
                    wd.Top = this.Top;
                    wd.Left = this.Left - wd.Width + 50;
                }
            }
        }
    }
}
